import Modal from '../ui/Modal';
import Table from '../ui/table';
import Dom from '../utils/Dom';
import Http from '../utils/Http';
import Config from '../config';
import Utils from '../utils/index';
import Events from '../utils/Events';

class MasterDataModal {
   constructor(table, Gantt) {
      // 主数据表及字段
      this.masterData = {
         facilities: {
            name: '设备维护',
            apiKey: 'facility',
            cols: [{
               key: 'sid',
               width: 50,
               name: '序号'
            }, {
               name: '编号',
               key: 'facilityCode'
            }, {
               name: '设备编码',
               key: 'facilityNo',
               search: true,
            }, {
               name: '设备名称',
               key: 'facilityDesc'
            }, {
               name: '工序编码',
               key: 'proccessNo',
               search: true
            }, {
               name: '设备分类',
               key: 'facilityType'
            }, {
               name: '设备简称',
               key: 'facilitySimpl'
            }, {
               name: '设备状态',
               key: 'machineStat'
            }, {
               name: '准备时间',
               key: 'setupTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '双工位交叉时间',
               width: 118,
               attrs: {
                  type: 'number'
               },
               key: 'overlapTime'
            }]
         },
         facilityTimeConfigs: {
            name: '设备时间维护',
            apiKey: 'facility-time-config',
            cols: [{
               name: '序号',
               key: 'sid'
            }, {
               name: '起始设备',
               key: 'startFacilityNo',
               search: true
            }, {
               name: '终止设备',
               key: 'endFacilityNo',
               search: true
            }, {
               name: '标准传搁时间',
               key: 'stdTransTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最小传搁时间',
               key: 'minTransTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最大传搁时间',
               key: 'maxTransTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '标准等待时间',
               key: 'stdWaitTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最小等待时间',
               key: 'minWaitTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最大等待时间',
               key: 'maxWaitTime',
               attrs: {
                  type: 'number'
               }
            }]
         },
         castSpeedConfigs: {
            name: '浇次速度维护',
            apiKey: 'cast-speed-config',
            cols: [{
               name: '序号',
               key: 'sid'
            }, {
               name: '出钢编号',
               key: 'caId',
               search: true
            }, {
               name: '出钢标记',
               key: 'caDescr'
            }, {
               name: '宽度',
               key: 'slabWidth',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '厚度',
               key: 'slabHeight',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最小周期',
               key: 'minProcessTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最大周期',
               key: 'maxProcessTime',
               attrs: {
                  type: 'number'
               }
            }]
         },
         castCaConfigs: {
            name: '异钢种连浇维护',
            apiKey: 'cast-ca-config',
            cols: [{
               name: '序号',
               key: 'sid'
            }, {
               name: '出钢编号（1）',
               key: 'caId1',
               search: true
            }, {
               name: '出钢标记（1）',
               key: 'caDescr1'
            }, {
               name: '出钢编号（2）',
               key: 'caId2',
               search: true
            }, {
               name: "出钢标记（2）",
               key: 'caDescr2'
            }, {
               name: '允许',
               key: 'allow',
               attrs: {
                  type: 'number'
               }
            }]
         },
         operationTimeConfigs: {
            name: '作业时间维护',
            apiKey: 'operation-time-config',
            cols: [{
               name: '序号',
               key: 'sid',
               width: 75
            }, {
               name: '设备编号',
               key: 'facilityNo',
               width: 60
            }, {
               name: '工艺路径号',
               key: 'routeId',
               width: 150
            }, {
               name: '出钢编号',
               key: 'caId',
               search: true
            }, {
               name: '出钢标记',
               key: 'caDescr'
            }, {
               name: '标准处理时间',
               key: 'stdProcessTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '过程编号',
               key: 'proccessNo'
            }, {
               name: '最大处理时间',
               key: 'maxProcessTime',
               attrs: {
                  type: 'number'
               }
            }, {
               name: '最小处理时间',
               key: 'minProcessTime',
               attrs: {
                  type: 'number'
               }
            }]
         },
         facilityRepairs: {
            name: '设备检修时间配置',
            apiKey: 'facility-repair',
            cols: [{
               name: '序号',
               key: 'sid'
            }, {
               name: '设备编码',
               key: 'facilityNo',
               search: true
            }, {
               name: '设备名称',
               key: 'facilityDesc'
            }, {
               name: '开始时间',
               key: 'repairStartTmstamp',
               attrs: {
                  type: 'datetime-local',
                  step: 1
               }
            }, {
               name: '结束时间',
               key: 'repairEndTmstamp',
               attrs: {
                  type: 'datetime-local',
                  step: 1
               }
            }, {
               name: '内容',
               key: 'remark',
               longtext: true
            }]
         }
      };

      this.Gantt = Gantt;
      this.modal = null;

      // 当前编辑的对象
      this.currentObj = null;

      // 是否需要通知甘特图重绘，目前的只考虑设备数据更新的情况
      this.needNotify = false;

      this.init(table);
   }

   init(table) {
      if (!this.modal) {
         this.modal = new Modal(this.masterData[table].name, body => {

            let p = Dom.append(body, 'div', 'modal-search', '<span class="label">搜索：</span>');

            this.searchContainer = Dom.append(p, 'span');
            this.searchBtn = Dom.append(p, 'span', null, '<button class="js-btn js-btn-success">搜索</button><button class="js-btn">取消</button>');

            Dom.addEvent(this.searchBtn, 'click', e => {
               if (e.target.tagName === 'BUTTON') {
                  this.search(e.target.className.indexOf('btn-success') === -1);
               }
               return Dom.nodefault(e);
            });

            this.tableContainer = Dom.append(body, 'div', 'modal-table');

            this.paginationContainer = Dom.append(body, 'div', 'modal-pagination');

            this.editContainer = Dom.append(body, 'div', 'modal-edit');

         }, index => {
            switch (index) {
               case 0: // 新建
                  this.currentObj = {};
                  if (this.datatable) {
                     this.datatable.clearSelection();
                  }
                  this.edit();
                  break;
               case 1: // 删除
                  this.remove();;
                  break;
               case 2: // 保存
                  this.save();;
                  break;
               case 3: // 关闭
                  this.modal.show(true);
                  if (this.needNotify) {
                     this.notifyUpdate();
                  }
                  break;
            }
         }, {
            className: 'modal-extra-large',
            buttons: ['新建', '删除', '保存', '关闭']
         });

      }

      this.setTable(table);
   }

   // 更新表
   setTable(table) {
      this.modal.show();
      this.currentObj = null;
      this.needNotify = false;
      if (this.datatable) {
         this.datatable.clearSelection();
      }

      if (this.table === table) {
         this.search(true);
         this.edit();
         return false;
      }

      if (document.body.clientHeight < 600) {
         if (this.modal.modal.className.indexOf('small-modal') === -1) {
            this.modal.modal.className += ' small-modal';
         }
      } else {
         if (this.modal.modal.className.indexOf('small-modal') !== -1) {
            this.modal.modal.className = this.modal.modal.className.replace(' small-modal', '')
         }
      }

      this.table = table;
      this.page = {
         num: 1,
         size: 100
      };

      this.editContainer.innerHTML = '';
      if (this.datatable) {
         this.datatable.destory();
         this.datatable = null;
         this.tableContainer.innerHTML = '';
      }

      this.modal.title.innerText = this.masterData[table].name;
      // 搜索区
      let input = null;
      this.searchContainer.innerHTML = '';
      this.masterData[table].cols.forEach(col => {
         if (col.search) {
            input = Dom.append(this.searchContainer, 'input', null, null, null, {
               placeholder: col.name
            });
            input.dataKey = col.key;
         }
      });
      this.loadData();
   }

   // 加载数据
   loadData(isCancle) {
      let params = {
         page: this.page.num,
         limit: this.page.size
      };

      this.searchContainer.childNodes.forEach(input => {
         if (isCancle) {
            input.value = null;
         } else if (input.value) {
            params['qm.' + input.dataKey] = input.value;
         }
      });

      Http.get(Config.api.singleMasterData.query.replace('{key}', this.masterData[this.table].apiKey), params, data => {
         if (!this.datatable) {
            this.datatable = new Table(this.tableContainer, this.masterData[this.table].cols, data.items, {
               className: 'master-data-table',
               trValueKey: 'version',
               selectedCallback: tr => {
                  this.currentObj = {
                     version: parseInt(tr.getAttribute('data-version'))
                  };
                  this.masterData[this.table].cols.forEach((col, index) => {
                     this.currentObj[col.key] = tr.childNodes[index].innerHTML;
                  });
                  this.edit();
               }
            });
         } else {
            this.datatable.setData(data.items);
         }

         this.page.total = Math.ceil(data.totalProperty / this.page.size);
         this.page.isFirst = this.page.num === 1;
         this.page.isLast = this.page.num === this.page.total;

         this.currentObj = null;
         this.edit();

         this.pagination();
      });
   }

   // 更新分页信息
   pagination() {
      if (this.page.total > 1) {

         let ulStr = '<ul><li data-index="1" ' + (this.page.isFirst ? 'class="disabled"' : '') + ' title="返回第一页">«</li>',
            start = 1,
            end = this.page.total,
            className = '';

         if (this.page.total > 10) {
            if (this.page.num > 5 && this.page.num < this.page.total - 4) {
               start = this.page.num - 5;
               end = this.page.num + 4;
            } else {
               if (this.page.num <= 5) {
                  start = 1;
                  end = 10;
               } else {
                  end = this.page.total;
                  start = this.page.total - 9;
               }
            }
         }

         for (; start <= end; start++) {
            className = start === this.page.num ? 'class="active"' : '';
            ulStr += '<li data-index="' + start + '" ' + className + ' title="跳转到第 ' + start + ' 页">' + start + '</li>';
         }

         ulStr += '<li data-index="' + this.page.total + '" ' + (this.page.isLast ? 'class="disabled"' : '') + ' title="最后一页">»</li>' +
            '</ul>' +
            '<span class="page-info">当前第 ' + this.page.num + ' 页，共 ' + this.page.total + ' 页，每页 ' + this.page.size + ' 条记录</span>';
         this.paginationContainer.innerHTML = ulStr;
         this.paginationContainer.style.display = 'block';
      } else {
         this.paginationContainer.style.display = 'none';
      }

      if (!this.paginationEvent) {
         this.paginationEvent = Dom.addEvent(this.paginationContainer, 'click', e => {
            if (e.target.tagName === 'LI') {
               this.goto(parseInt(e.target.getAttribute('data-index')));
            }
            return Dom.nodefault(e);
         });
      }
   }


   remove() {
      let i = 0,
         total = this.editContainer.childNodes.length,
         input = null,
         sid = null;
      for (; i < total; i++) {
         input = this.editContainer.childNodes[i];
         if (input.childNodes[1].dataKey === 'sid') {
            sid = parseInt(input.childNodes[1].value);
            break;
         }
      }

      if (sid) {
         Http.post(Config.api.singleMasterData.remove.replace('{key}', this.masterData[this.table].apiKey), JSON.stringify({
            sid: sid
         }), data => {
            this.page.num = 1;
            this.loadData();
            this.Gantt.cache.remove(this.table, sid);
            this.needNotify = true;
         });
      }
   }

   save() {
      let obj = {},
         url = null,
         isUpdate = false,
         isDatetime = false,
         index = null,
         isNum = false,
         col = null;

      this.editContainer.childNodes.forEach((input) => {

         if (input.childNodes.length === 0) {
            if (input.value !== "") {
               obj[input.dataKey] = parseInt(input.value);
            }
            return;
         }

         if (input.childNodes[1].value === "") {
            return;
         }

         index = parseInt(input.getAttribute('data-index'));
         col = this.masterData[this.table].cols[index];
         isNum = col.key === 'sid' || (col.attrs && col.attrs.type === 'number');

         isDatetime = col.attrs && col.attrs.type === 'datetime-local';

         obj[input.childNodes[1].dataKey] =
            isNum ? parseInt(input.childNodes[1].value) : (
               isDatetime ? Utils.dateFill(input.childNodes[1].value) : input.childNodes[1].value
            );
      });

      isUpdate = obj.sid !== undefined;

      url = Config.api.singleMasterData[isUpdate ? 'update' : 'add'];

      Http.post(url.replace('{key}', this.masterData[this.table].apiKey), JSON.stringify(obj), data => {
         this.needNotify = true;
         if (isUpdate) {
            this.Gantt.cache.update(this.table, data);
         } else {
            this.Gantt.cache.insert(this.table, data);
         }
         this.loadData();
         // 更新缓存
      });
   }

   // 跳转到分页
   goto(page) {
      if (page === this.page.num || page < 1 || page > this.page.total) {
         return false;
      }

      this.page.num = page;

      this.loadData();
   }

   // 搜索
   search(isCancle) {
      this.page.num = 1;
      this.loadData(isCancle);
   }

   // 主数据有变动则通知图形进行更新
   notifyUpdate() {
      // 目前只有设备数据需要通知
      if (this.table === 'facilities') {
         Events.emit('masterDataUpdated');
      } else if (this.table === 'facilityRepairs') {
         Events.emit('facilityRepairsUpdated');
      }
   }

   // 编辑
   edit() {
      let buttonsStatus = [
         // 按钮下标，是否是禁用
         [1, false],
         [2, false]
      ];

      if (this.currentObj) {
         let needCreate = this.editContainer.innerHTML === '',
            p = null,
            input = null,
            i = 0,
            total = this.masterData[this.table].cols.length,
            col = null,
            valueUpdated = null;

         for (; i < total; i++) {
            valueUpdated = false;
            col = this.masterData[this.table].cols[i];
            if (needCreate) {
               p = Dom.append(this.editContainer, 'div', 'item', '<span class="label">' + col.name + '</span>');
               p.setAttribute('data-index', i);

               
               if (this.table=="operationTimeConfigs") {
                  let selectOptions = '';
                  if(col.key&&(col.key=="facilityNo"||col.key=="proccessNo")){
                     selectOptions = '<option value="BOF">BOF</option> <option value="LF">LF</option> <option value="VD">VD</option>';
                     input = Dom.append(p, 'select', null, selectOptions);
                     Dom.addEvent(input,'change',e => {
                        if('BOF' == e.target.value){
                           Dom.get('stdProcessTime').value=1680;
                           Dom.get('maxProcessTime').value=2100;
                           Dom.get('minProcessTime').value=1600;
                        }else{
                           Dom.get('stdProcessTime').value=1800;
                           Dom.get('maxProcessTime').value=2100;
                           Dom.get('minProcessTime').value=1750;
                        }
                     });
                  }else if(col.key&&col.key=="routeId"){
                     selectOptions = '<option value="BOF_LF_SCM">BOF_LF_SCM</option> <option value="BOF_LF_VD_SCM">BOF_LF_VD_SCM</option> <option value="BOF_VD_LF_SCM">BOF_VD_LF_SCM</option> <option value="BOF_VD_SCM">BOF_VD_SCM</option>';
                     input = Dom.append(p, 'select', null, selectOptions);
                  }else if(col.key&&col.key=="stdProcessTime"){
                     input = Dom.append(p, col.longtext ? 'textarea' : 'input', null);
                     input.setAttribute('id', 'stdProcessTime');
                  }else if(col.key&&col.key=="maxProcessTime"){
                     input = Dom.append(p, col.longtext ? 'textarea' : 'input', null);
                     input.setAttribute('id', 'maxProcessTime');
                  }else if(col.key&&col.key=="minProcessTime"){
                     input = Dom.append(p, col.longtext ? 'textarea' : 'input', null);
                     input.setAttribute('id', 'minProcessTime');
                  }else{
                     input = Dom.append(p, col.longtext ? 'textarea' : 'input', null);
                  }
               }else{
                  input = Dom.append(p, col.longtext ? 'textarea' : 'input', null);
               }

               

               if (col.longtext) {
                  p.className += ' item-large';
               }
            } else {
               input = this.editContainer.childNodes[i].childNodes[1];
            }

            input.dataKey = col.key;
            if (col.key === 'sid') {
               input.setAttribute('readonly', true);
               if (p) {
                  p.style.display = 'none';
               }

               col.attrs = {
                  type: 'number'
               }
            }

            if (col.attrs) {
               Dom.setAttr(input, col.attrs);
               if (col.attrs.type === 'datetime-local') {
                  input.value = (this.currentObj[col.key] || Utils.dateFormat(null, '-', true)).replace(' ', 'T');
                  valueUpdated = true;
               }
            }

            if (!valueUpdated) {
               input.value = this.currentObj[col.key] || null;
            }
         }

         // version
         if (needCreate) {
            input = Dom.append(this.editContainer, 'input');
            input.style.display = 'none';
            input.dataKey = 'version';
            input.type = 'number';
         } else {
            input = this.editContainer.childNodes[this.editContainer.childNodes.length - 1];
         }

         input.value = this.currentObj.version || null;

         this.editContainer.style.display = 'block';

         // 删除、保存 启用
         if (Utils.isObjEmpty(this.currentObj)) { // 新建
            buttonsStatus[0][1] = true;
         } // 更新
      } else { // 其他
         this.editContainer.style.display = 'none';
         buttonsStatus[0][1] = true;
         buttonsStatus[1][1] = true;
      }

      buttonsStatus.forEach(status => {
         if (status[1]) {
            if (this.modal.buttons[status[0]].className.indexOf('disabled') == -1) {
               this.modal.buttons[status[0]].className += ' disabled';
            }
         } else {
            this.modal.buttons[status[0]].className = this.modal.buttons[status[0]].className.replace(' disabled', '');
         }
      });
   }
}

export default MasterDataModal;